<template>
    <div class="p-grid crud-demo">
        <div class="p-col-12 p-md-12">

            <!--面包屑-->
            <div style="padding-bottom: 0.95rem;">
                <Breadcrumb :home="home" :model="crumbs"/>
            </div>

            <!--标签栏-->
            <div class="card">
                <h4>系统配置</h4>
                <p>可以在此增改系统的变量和分组,也可以自定义分组和变量,如果需要删除请从数据库中删除。</p>

                <!--标签栏--按钮组-->
                <Toast/>
                <Toolbar class="p-mb-12">
                    <template slot="left">
                        <Button label="新建分组" icon="pi pi-plus" class="p-button-success p-mr-2" @click="openNew"/>
                        <Button label="添加参数" icon="pi pi-plus" class="p-button-info p-mr-2" @click="openNew"/>
                    </template>
                </Toolbar>

                <TabView style="margin-top: 10px;">
                    <b v-for="(item,index) in groups" :key="index">
                        <TabPanel :header="item.title">
                            <div class="p-col-12 p-md-10" style="padding: 0">
                                <div class="card p-fluid" style="padding: 0">
                                    <div v-for="(item2,index2) in item.lists" :key="index2">
                                        <template v-if="item2.group === item.group">

                                            <template v-if="item2.type==='string'">
                                                <div class="p-field">
                                                    <label :for="item2.name">{{item2.title}}</label>
                                                    <InputText :id="item2.name" v-model="item2.value" type="text"
                                                               :placeholder="item2.tip"
                                                               :required="item2.rule === 'required'"/>
                                                </div>
                                            </template>

                                            <template v-else-if="item2.type==='text'">
                                                <div class="p-field">
                                                    <label :for="item2.name">{{item2.title}}</label>
                                                    <Textarea :id="item2.name" v-model="item2.value" rows="5" cols="30"
                                                              :placeholder="item2.tip"/>
                                                </div>
                                            </template>

                                            <template v-else-if="item2.type==='editor'">
                                                <div class="p-field">
                                                    <label :for="item2.name">{{item2.title}}</label>
                                                    <Editor :id="item2.name" v-model="item2.value"
                                                            editorStyle="height: 300px" :placeholder="item2.tip"/>
                                                </div>
                                            </template>

                                            <template v-else-if="item2.type==='switch'">
                                                <div class="p-field">
                                                    <label :for="item2.name">{{item2.title}}</label>
                                                    <div class="p-field p-col">
                                                        <InputSwitch v-model="item2.value"/>
                                                    </div>
                                                </div>
                                            </template>

                                            <template v-else-if="item2.type==='array'">
                                                <label :for="item2.name" style="line-height: 20px;">{{item2.title}}</label>
                                                <div v-for="(item3,index3) in groups[index].lists[index2].value" :key="index3">
                                                    <Button style="width: 70px;" v-show="index3===0" @click="addArrInput(index,index2,index3, groups[index].lists[index2].value)" class="p-button-success">追加元素</Button>
                                                    <div :id="'delArrInput_'+index3" class="p-formgrid p-grid" v-show="groups[index].lists[index2].value[index3]!==null">
                                                        <div class="p-field p-col">
                                                            <label :for="index3">键名</label>
                                                            <InputText :id="index3" v-model="item3.key" type="text" placeholder="请输入键名"/>
                                                        </div>
                                                        <div class="p-field p-col">
                                                            <label :for="item3">键值</label>
                                                            <InputText :id="item3" v-model="item3.value" type="text" placeholder="请输入键值"/>
                                                        </div>
                                                        <div class="p-field p-col">
                                                            <label :for="item2.name">操作</label>
                                                            <Button @click="delArrInput(index,index2,index3)"  label="删除" class="p-button-secondary" icon="pi pi-times" iconPos="left"/>
                                                        </div>

                                                    </div>
                                                </div>
                                            </template>

                                            <template v-else-if="item2.type==='image'">
                                                <div class="p-field">
                                                    <label :for="item2.name">{{item2.title}}##{{index}}##{{index2}}</label>
                                                    <div class="p-field p-col">
                                                        <input ref="filElem2" :class="'image_'+index+'_'+index2" @change='updateImgChange' type="file">
                                                        <img v-show="item2.value !== null"  width="150px" :src="item2.value" :alt="item2.name" onerror="this.src='assets/demo/images/avatar/kongbai.png'">
                                                    </div>
                                                </div>
                                            </template>

                                            <template v-else>
                                                <div class="p-field">
                                                    <label :for="item2.name">默认！！！！{{item2.title}}</label>
                                                    <InputText :id="item2.name" v-model="item2.value" type="text"
                                                               :placeholder="item2.tip"
                                                               :required="item2.rule === 'required'"/>
                                                </div>
                                            </template>

                                        </template>
                                    </div>
                                    <Button label="保存" @click="submit"/>
                                </div>
                            </div>
                        </TabPanel>
                    </b>
                </TabView>


                <Dialog :visible.sync="listDialog" :style="{width: '450px'}" header="产品详情" :modal="true"
                        class="p-fluid">
                    <img :src="'assets/demo/images/list/' + list.image" :alt="list.image" class="list-image"
                         v-if="list.image"/>
                    <div class="p-field">
                        <label for="name">名称</label>
                        <InputText id="name" v-model.trim="list.name" required="true" autofocus
                                   :class="{'p-invalid': submitted && !list.name}"/>
                        <small class="p-invalid" v-if="submitted && !list.name">名称是必须的。</small>
                    </div>
                    <div class="p-field">
                        <label for="description">描述</label>
                        <Textarea id="description" v-model="list.description" required="true" rows="3" cols="20"/>
                    </div>

                    <div class="p-field">
                        <label class="p-mb-3">分类</label>
                        <div class="p-formgrid p-grid">
                            <div class="p-field-radiobutton p-col-6">
                                <RadioButton id="category1" name="category" v-model="list.category"/>
                                <label for="category1">穿戴配饰</label>
                            </div>
                            <div class="p-field-radiobutton p-col-6">
                                <RadioButton id="category2" name="category" v-model="list.category"/>
                                <label for="category2">服装</label>
                            </div>
                            <div class="p-field-radiobutton p-col-6">
                                <RadioButton id="category3" name="category" v-model="list.category"/>
                                <label for="category3">电子产品</label>
                            </div>
                            <div class="p-field-radiobutton p-col-6">
                                <RadioButton id="category4" name="category" v-model="list.category"/>
                                <label for="category4">小饰品</label>
                            </div>
                        </div>
                    </div>

                    <div class="p-formgrid p-grid">
                        <div class="p-field p-col">
                            <label for="price">价格</label>
                            <InputNumber id="price" v-model="list.price" mode="currency" currency="USD"
                                         locale="en-US"/>
                        </div>
                        <div class="p-field p-col">
                            <label for="quantity">数量</label>
                            <InputNumber id="quantity" v-model="list.quantity" integeronly/>
                        </div>
                    </div>
                    <template #footer>
                        <Button label="取消" icon="pi pi-times" class="p-button-text" @click="hideDialog"/>
                        <Button label="保存" icon="pi pi-check" class="p-button-text" @click="savelist"/>
                    </template>
                </Dialog>

                <Dialog :visible.sync="deletelistDialog" :style="{width: '450px'}" header="确认" :modal="true">
                    <div class="confirmation-content">
                        <i class="pi pi-exclamation-triangle p-mr-3" style="font-size: 2rem"/>
                        <span v-if="list">确认删除 <b>{{list.name}}</b>?</span>
                    </div>
                    <template #footer>
                        <Button label="否" icon="pi pi-times" class="p-button-text"
                                @click="deletelistDialog = false"/>
                        <Button label="是" icon="pi pi-check" class="p-button-text" @click="deletelist"/>
                    </template>
                </Dialog>

            </div>
        </div>
    </div>


</template>

<script>
    import TableService from '@/api/TableService';
    import UploadService from '@/api/UploadService';
    export default {
        data() {
            return {
                UploadService:null,
                paymentOptions: [
                    {name: '删除', value: 1},
                    {name: '移动', value: 2},
                ],
                groups: null,
                screenWidth: document.body.clientWidth, // 屏幕宽度
                scrollable: false,  //列表是否可滚动，屏幕宽度低于960时启用移动端预览模式，切换为：fasle
                //时间选择器
                dates2: null,
                zh: {
                    firstDayOfWeek: 0,
                    dayNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
                    dayNamesShort: ["日", "一", "二", "三", "四", "五", "六"],
                    dayNamesMin: ["日", "一", "二", "三", "四", "五", "六"],
                    monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                    monthNamesShort: ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"],
                    today: '今天',
                    clear: '清空',
                    dateFormat: 'mm-dd-yy',
                    weekHeader: '周'
                },
                minDate: null,
                maxDate: null,
                invalidDates: null,

                lists: null,
                empty: '没有找到匹配的记录',
                listDialog: false,
                deletelistDialog: false,
                deletelistsDialog: false,
                submitted: false,
                list: {},
                selectedlists: null,
                oldsearch: '',
                search: '', //快捷搜索--字段
                filter: {},//高级搜索--字段
                op: {},//高级搜索--条件
                loading: false,
                limit: 10, //分页，每页数量
                offset: 0, //从第几行开始
                totalItemsCount: 0,  //共多少条数据
                sort: 'id',  //排序键名
                order: 'desc',  //排序方式
                dataKey: 'id',//唯一字段，（主键）

                advSearchIcon: '',  //高级搜索选中时的icon
                visibleRight: false,  //弹出高级搜索选项
                advSearchs: {  //高级搜索字段
                    username: '',
                    mobile: '',
                    created_at: null,
                },
                controlRout: '/setting', //控制器
                home: {label: '控制台', icon: 'pi pi-home', to: '/'}, //面包屑公共导航
                crumbs: [ //面包屑
                ],
                defaultItems: [ //默认选项卡
                    {
                        label: '全部', icon: 'pi pi-fw pi-home', class: 'p-highlight',
                        command: (event) => {
                            this.setTabChecked(event);
                            this.clearFilter();
                            this.getListsTable();
                        }
                    }
                ],
                tabmenuItems: null, //动态选项卡
            }
        },
        TableService: null,
        created() {
            //时间选择器初始化
            let today = new Date();
            let month = today.getMonth();
            let year = today.getFullYear();
            let prevMonth = (month === 0) ? 11 : month - 1;
            let prevYear = (prevMonth === 11) ? year - 1 : year;
            let nextMonth = (month === 11) ? 0 : month + 1;
            let nextYear = (nextMonth === 0) ? year + 1 : year;
            this.minDate = new Date();
            this.minDate.setMonth(prevMonth);
            this.minDate.setFullYear(prevYear);
            this.maxDate = new Date();
            this.maxDate.setMonth(nextMonth);
            this.maxDate.setFullYear(nextYear);

            let invalidDate = new Date();
            invalidDate.setDate(today.getDate() - 1);
            this.invalidDates = [today, invalidDate];
            this.scrollable = document.body.clientWidth > 960;
            this.TableService = new TableService();
            this.tabmenuItems = this.defaultItems;
            this.UploadService = new UploadService();

            //获取当前路由名称
            for (let i = 0; i < this.$router.options.routes[1].children.length; i++) {
                if (this.$router.options.routes[1].children[i].path === this.$route.fullPath) {
                    this.crumbs = [
                        {label: '基础管理',},
                        {label: this.$router.options.routes[1].children[i].meta.title},
                    ];
                }
            }
        },
        mounted() {
            this.getListsTable();
            // 监听窗口大小
            window.onresize = () => {
                return (() => {
                    this.screenWidth = document.body.clientWidth
                })()
            };
        },
        methods: {
            updateImgChange(event)  //上传图片
            {
                let check = this.UploadService.check(event);
                if (check.code !== 20000) {
                    this.$toast.add({severity: 'info', summary: '提示', detail: check.msg, life: 3000});
                    return;
                }
                this.UploadService.post(check.data).then(data => {
                    console.log('data:' + JSON.stringify(data));
                    if (data.code !== 20000) {
                        this.$toast.add({severity: 'info', summary: '提示', detail: data.msg, life: 3000});
                        return;
                    }
                    let index = event.target._prevClass.split('_');
                    console.log('index:'+JSON.stringify(index));
                    this.groups[index[1]].lists[index[2]].value = data.data[0].full_path;
                });
            },
            delArrInput(index,index2,index3)  //删除数组输入框
            {
                this.groups[index].lists[index2].value[index3] = null;
                document.getElementById("delArrInput_"+index3).style.display="none";
            },
            addArrInput(index,index2,index3, array)
            {
                console.log('count:'+this.groups[index].lists[index2].value.length+'---array:'+JSON.stringify(array));
                this.groups[index].lists[index2].value[this.groups[index].lists[index2].value.length+1].key = 'test';
                this.groups[index].lists[index2].value[this.groups[index].lists[index2].value.length+1].value = '666';
                // document.getElementById("delArrInput_"+3).style.display="block";
            },
            submit() {
                // console.log('ttttt:'+JSON.stringify(this.groups[0].lists[6].value[1]));
                // this.groups[0].lists[6].value[1] = null;
                // groups[index].lists[index2].value[index3]

                console.log('t:' + JSON.stringify(this.groups));
            },
            getListsTable()  //获取表格数据
            {
                this.empty = '没有找到匹配的记录';
                let params = {
                    search: this.search,
                    filter: this.filter,
                    op: this.op,
                    limit: this.limit,
                    offset: this.offset,
                    sort: this.sort,
                    order: this.order,
                };
                this.loading = true;
                this.lists = null;
                this.totalItemsCount = 0;
                this.TableService.get(this.controlRout + '/list', params).then(data => {
                    // console.log('data:'+JSON.stringify(data));
                    if (data === undefined) {
                        this.empty = 'ERROR: 结果返回异常';
                        this.loading = false;
                        return;
                    } else if (typeof (data) === 'object' && data.code !== 20000) {
                        this.empty = 'ERROR: ' + data.msg;
                        this.loading = false;
                        return;
                    }

                    this.groups = data.data.groups;

                });
            },
            openNew() {
                this.list = {};
                this.submitted = false;
                this.listDialog = true;
            },
            hideDialog() {
                this.listDialog = false;
                this.submitted = false;
            },
            savelist() {
                this.submitted = true;

                if (this.list.name.trim()) {
                    if (this.list.id) {
                        this.$set(this.lists, this.findIndexById(this.list.id), this.list);
                        this.$toast.add({severity: 'success', summary: '提示', detail: '更新成功', life: 3000});
                    } else {
                        this.list.id = this.createId();
                        this.list.code = this.createId();
                        this.list.image = 'list-placeholder.svg';
                        this.list.inventoryStatus = 'INSTOCK';
                        this.lists.push(this.list);
                        this.$toast.add({severity: 'success', summary: '提示', detail: '新建成功', life: 3000});
                    }

                    this.listDialog = false;
                    this.list = {};
                }
            },
            editlist(list) {
                this.list = {...list};
                this.listDialog = true;
            },
        },
        watch: {
            screenWidth(val) {
                this.scrollable = val > 960;   //适配移动端预览，关闭滚动列表
            },
            search(val)  //搜索框
            {
                if (val.replace(/^\s+|\s+$/g, "") === this.oldsearch.replace(/^\s+|\s+$/g, "")) {
                    return; //解决输入文字时无效提交
                }
                this.oldsearch = val;
                this.getListsTable({search: true});
            }
        },
    }
</script>

<style scoped lang="scss">
    .table-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .confirmation-content {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .list-badge {
        border-radius: 2px;
        padding: .25em .5rem;
        text-transform: uppercase;
        font-weight: 700;
        font-size: 12px;
        letter-spacing: .3px;

        &.status-有现货 {
            background: #C8E6C9;
            color: #256029;
        }

        &.status-缺货 {
            background: #FFCDD2;
            color: #C63737;
        }

        &.status-lowstock {
            background: #FEEDAF;
            color: #8A5340;
        }
    }

    @media screen and (max-width: 960px) {
        /deep/ .p-datatable {
            &.p-datatable-customers {
                .p-datatable-thead > tr > th,
                .p-datatable-tfoot > tr > td {
                    display: none !important;
                }

                .p-datatable-tbody > tr {
                    border-bottom: 1px solid var(--surface-d);

                    > td {
                        text-align: left;
                        display: block;
                        border: 0 none !important;
                        width: 100% !important;
                        float: left;
                        clear: left;
                        border: 0 none;

                        .p-column-title {
                            padding: .4rem;
                            min-width: 30%;
                            display: inline-block;
                            margin: -.4rem 1rem -.4rem -.4rem;
                            font-weight: bold;
                        }

                        .p-progressbar {
                            margin-top: .5rem;
                        }
                    }
                }
            }
        }

        /deep/ .p-toolbar {
            flex-wrap: wrap;

            .p-button {
                margin-bottom: .25rem;
            }
        }
    }

    .tabview-custom {
        i, span {
            vertical-align: middle;
        }

        span {
            margin: 0 .5rem;
        }
    }

    .p-multiselect {
        min-width: 15rem;
    }

    .multiselect-custom {

        .p-multiselect-label:not(.p-placeholder) {
            padding-top: .25rem;
            padding-bottom: .25rem;
        }

        .country-item {
            display: flex;
            align-items: center;

            span.flag {
                width: 18px;
                height: 12px;
                margin-right: .5rem;
                margin-left: .5rem;
            }
        }

        .country-item-value {
            border-radius: 3px;
            display: inline-flex;
            margin-right: .5rem;
            background-color: var(--primary-color);
            color: var(--primary-color-text);
        }
    }

    .special-day {
        text-decoration: line-through;
    }

    /**
    小头像
     */
    .img-center {
        margin: 0 auto;
        display: inline;
        float: none;
    }

    .img-sm-sm, .box-comments .box-comment img, .user-block.user-block-sm img {
        width: 2.8rem !important;
        height: 2.8rem !important;
    }

    /**
    切换开关
     */
    .p-button.p-highlight {
        background: #2196F3;
        border-color: #2196F3;
        color: #ffffff;
    }

    .p-button:not(.p-disabled):not(.p-highlight):hover {
        background: #e9ecef;
        border-color: #ced4da;
        color: #495057;
    }

    /**
    标签卡
     */
    .status-success {
        background: #c8e6c9;
        color: #256029;
    }

    .p-tabview-panels {
        padding: 0;
    }
</style>
